export async function startFetchStream(url: string) {
  try {
    const response = await fetch(url);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // 将响应体的流传递给回调函数进行处理
    handleStream(response.body);
  } catch (error) {
    console.error("Fetch error:", error);
  }
}

async function handleStream(
  stream: ReadableStream<Uint8Array<ArrayBufferLike>> | null
) {
  const reader = stream?.getReader();
  const decoder = new TextDecoder("utf-8");
  let buffer = "";
  let bufferObj: Record<string, any>;
  let isFirstMessage = true;

  while (true) {
    const { done, value } = (await reader?.read()) || {};
    if (done) {
      console.log('sse done')
      break;
    }

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split("\n");

    for (let i = 0; i < lines.length - 1; i++) {
      const message = lines[i].trim();
      if (message.startsWith("data: ")) {
        console.log(message);
      }
    }

    // 保留未完整处理的最后一行
    buffer = lines[lines.length - 1];
  }
}
